package com.wmlive.hhvideo.heihei.mainhome.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.model.OSSRequest;
import com.wmlive.hhvideo.common.base.DcBaseFragment;
import com.wmlive.hhvideo.common.ossutils.UpLoadInterface;
import com.wmlive.hhvideo.common.ossutils.UploadALiResultBean;
import com.wmlive.hhvideo.common.ossutils.UploadPresenter;
import com.wmlive.hhvideo.heihei.beans.opus.OpusPublishRequestBean;
import com.wmlive.hhvideo.heihei.discovery.activity.DiscoveryActivity;
import com.wmlive.hhvideo.heihei.login.AccountUtil;
import com.wmlive.hhvideo.heihei.mainhome.adapter.MainFragmentPageAdapter;
import com.wmlive.hhvideo.heihei.recordvideo.DyUIAPICallbackImpl;
import com.wmlive.hhvideo.utils.KLog;
import com.wmlive.hhvideo.utils.ToastUtil;
import com.wmlive.hhvideo.utils.imageloader.GlideLoader;
import com.wmlive.hhvideo.widget.UnScrollViewPager;

import java.lang.ref.WeakReference;

import butterknife.BindView;
import cn.wmlive.hhvideo.R;
import cn.wmlive.hhvideo.rxbuslib.RxBus2;


/**
 * A simple {@link Fragment} subclass.
 * 首页
 * Modify by lsq
 */
public class MainFragment extends DcBaseFragment implements UpLoadInterface {

    @BindView(R.id.view_pager_home)
    UnScrollViewPager homePager;
    @BindView(R.id.tabSelect)
    TabLayout tabSelect;
    @BindView(R.id.tvDiscovery)
    ImageView tvDiscovery;
    @BindView(R.id.layout_upload_view)
    View layout_upload_view;
    @BindView(R.id.iv_upload_icon)
    ImageView iv_upload_icon;
    @BindView(R.id.iv_upload_icon_mask)
    ImageView iv_upload_icon_mask;
    @BindView(R.id.pb_upload_bar)
    ProgressBar pb_upload_bar;
    @BindView(R.id.tv_upload_num)
    TextView tv_upload_num;


    public MainFragmentPageAdapter pageAdapter;

    //上传作品
    private int uploadType = 0;//(1:上传视频  2：上传图片   3：上传动图 ，4 ：业务)
    private UploadPresenter uploadPresenter;
    private RefreshUploadHandler RefreshUploadHandler;
    public static int sMainFgTab = -1;//当前选中的tab
    private int iCurrentUploadProgress = -1;//上传的当前进度
    private int iRefreshUploadHandlerType = -1;//当前的操作类型(0：操作失败  1:开始导出  2 ：导出进度  3：导出成功  4：上传开始 5：上传进度 6：上传进度 7：上传完成  )
    private OpusPublishRequestBean opusPublishRequestBean;//上传作品信息类
    private static final String TAG = "MainFragment";


    @Override
    public int getLayoutId() {
        return R.layout.fragment_main;
    }

    @Override
    protected void initData() {
        super.initData();
        RxBus2.get().register(this);
        pageAdapter = new MainFragmentPageAdapter(getFragmentManager());
        homePager.setAdapter(pageAdapter);
//        tabSelect.setupWithViewPager(homePager);
//        tabSelect.addOnTabSelectedListener(new MyOnTabSelectedListener(this));
        tvDiscovery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isRecyclerScroll()) {
                    return;
                }
                startActivity(new Intent(getActivity(), DiscoveryActivity.class));
            }
        });
        //第三方回调信息初始化
        iCurrentUploadProgress = -1;
        sMainFgTab = -1;
        RefreshUploadHandler = new RefreshUploadHandler(this);
        initDyUIAPICallbackImpInfo();

        if (tabSelect.getTabAt(1) != null) {
            tabSelect.getTabAt(1).select();
            sMainFgTab = 1;
            homePager.setCurrentItem(1);
            showTabSelectedUI(tabSelect.getTabAt(1), true);
            showTVUploadProgress(false);
        }
        tabSelect.getTabAt(0).getCustomView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (sMainFgTab == 0 || isRecyclerScroll()) {
                    return;
                }
                if (!AccountUtil.isLogin()) {
                    showReLogin();
                } else {
                    sMainFgTab = 0;
                    showTabSelectedUI(tabSelect.getTabAt(0), true);
                    showTabSelectedUI(tabSelect.getTabAt(1), false);
                    showTabSelectedUI(tabSelect.getTabAt(2), false);
                    showTVUploadProgress(true);
                }
            }
        });

        tabSelect.getTabAt(1).getCustomView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (sMainFgTab == 1 || isRecyclerScroll()) {
                    return;
                }
                sMainFgTab = 1;
                showTabSelectedUI(tabSelect.getTabAt(0), false);
                showTabSelectedUI(tabSelect.getTabAt(1), true);
                showTabSelectedUI(tabSelect.getTabAt(2), false);
                showTVUploadProgress(false);
            }
        });

        tabSelect.getTabAt(2).getCustomView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (sMainFgTab == 2 || isRecyclerScroll()) {
                    return;
                }
                sMainFgTab = 2;
                showTabSelectedUI(tabSelect.getTabAt(0), false);
                showTabSelectedUI(tabSelect.getTabAt(1), false);
                showTabSelectedUI(tabSelect.getTabAt(2), true);
                showTVUploadProgress(false);
            }
        });
    }

    public boolean isRecyclerScroll() {
//        boolean scroll = !RecommendFragmentNew.isRecommendRecyclerIdle || !AttentionFragmentNew.isAttentionRecyclerIdle;
//        KLog.i("=====页面" + (scroll ? "在" : "未") + "滚动");
        return false;
    }

    @Override
    public void onDestroy() {
        RxBus2.get().unRegister(this);
        super.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (sMainFgTab == 0) {
            Fragment fragment = pageAdapter.getItem(0);
            if (null != fragment) {
                KLog.i("======调用关注页开始播放");
                ((AttentionFragmentNew) fragment).resumePlay();
            }
        } else if (sMainFgTab == 1) {
            Fragment fragment = pageAdapter.getItem(1);
            if (null != fragment) {
                KLog.i("======调用推荐页开始播放");
                ((RecommendFragmentNew) fragment).resumePlay();
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();//切换到其他Tab的时候会调用
    }


    @Override
    protected void onSingleClick(View v) {

    }

    /**
     * 初始化第三方录制回调信息
     */
    private void initDyUIAPICallbackImpInfo() {
        uploadPresenter = new UploadPresenter(this);
        uploadPresenter.setmUpLoadInterface(this);
        DyUIAPICallbackImpl.getInstance().setContext(getActivity());
        DyUIAPICallbackImpl.getInstance().setmCurrentCallbackHandler(RefreshUploadHandler);
    }


    /**
     * 说服显示进度条
     *
     * @param visible
     */
    private void showTVUploadProgress(boolean visible) {
        if (visible && iCurrentUploadProgress >= 0) {
            layout_upload_view.setVisibility(View.VISIBLE);
            showTVUploadProgressUI(2);
        } else {
            layout_upload_view.setVisibility(View.INVISIBLE);
        }
    }


    /**
     * 显示制定的tab
     *
     * @param tabPosition
     */
    public void showSelectTag(int tabPosition) {
        if (tabPosition < 0) {
            tabPosition = 0;
        } else if (tabPosition >= tabSelect.getTabCount()) {
            tabPosition = tabSelect.getTabCount() - 1;
        }
        if (tabSelect.getTabAt(tabPosition) != null) {
            tabSelect.getTabAt(tabPosition).select();
            sMainFgTab = tabPosition;
            homePager.setCurrentItem(tabPosition);
        }
    }

    /**
     * 导出开始
     */
    private void exportVideoStart(Bundle mBundle) {
        String strShortVideoFirstImgPath = "";
        //显示关注页面
        showSelectTag(2);
        //获取部上传作品数据
        opusPublishRequestBean = new OpusPublishRequestBean();
        if (mBundle != null) {
            opusPublishRequestBean.setTitle(mBundle.getString("title"));
            opusPublishRequestBean.setTopic_id(mBundle.getLong("topic_id"));
            opusPublishRequestBean.setMusic_id(mBundle.getLong("music_id"));
            opusPublishRequestBean.setOpus_length(mBundle.getFloat("opus_length"));
            opusPublishRequestBean.setOpus_gif_cover("");
            opusPublishRequestBean.setOpus_gif_cover_sign("");
            opusPublishRequestBean.setAt_user_ids(null);
            strShortVideoFirstImgPath = mBundle.getString("shorvideo_first_image");
        }
        //加载图片
        GlideLoader.loadImage(strShortVideoFirstImgPath, iv_upload_icon, R.drawable.ic_photo_loading);
        //显示上传进度
        refreshExportProgress(0);
        showTVUploadProgress(true);
    }

    /**
     * 更新导出进度
     *
     * @param progress
     */
    private void refreshExportProgress(int progress) {
        if (progress > -1) {
            iCurrentUploadProgress = progress;
            if (iCurrentUploadProgress >= 97) {
                iCurrentUploadProgress = 97;
            }
            tv_upload_num.setText(String.valueOf(iCurrentUploadProgress) + "%");
        }
    }

    /**
     * 导出完成
     *
     * @param mBundle
     */
    private void exportVideoEnd(Bundle mBundle) {
        if (mBundle != null) {
            String strLoadVideoPath = mBundle.getString("UploadPath");
            //开始上传
            uploadType = 1;
            uploadPresenter.setStrUploadPath(strLoadVideoPath);
            uploadPresenter.getOSSTokenAndUploadInfo("opus", "mp4");
        }
    }

    /**
     * 刷新进度
     */
    private synchronized void refreshUploadProgress(int progress) {
        if (progress > -1) {
            iCurrentUploadProgress = iCurrentUploadProgress + progress;
            if (iCurrentUploadProgress >= 100) {
                iCurrentUploadProgress = 100;
            }
        }
        tv_upload_num.setText(String.valueOf(iCurrentUploadProgress) + "%");
    }


    /**
     * 上传完成
     */
    private void refreshUpdateFinish() {
        if (tv_upload_num != null) {
            iCurrentUploadProgress = -1;
            showTVUploadProgressUI(1);
        }
        DyUIAPICallbackImpl.getInstance().deletDraftBoxVideoInfo();
    }

    /**
     * 上传完成刷新UI
     */
    private void refreshUpdateFinishUI() {
        showTVUploadProgressUI(0);
        showToast(R.string.publish_succeed);
    }

    /**
     * 上传错误
     */
    private void refreshUpdateError() {
        if (tv_upload_num != null) {
            iCurrentUploadProgress = -1;
            ToastUtil.showToast("上传作品失败，请到草稿箱中查看");
            showTVUploadProgressUI(0);
        }
    }

    /**
     * @param type（0：全部隐藏 1：隐藏上传进度   2：全部显示）
     */
    private void showTVUploadProgressUI(int type) {
        if (type == 2) {
            iv_upload_icon.setVisibility(View.VISIBLE);
            iv_upload_icon_mask.setVisibility(View.VISIBLE);
            pb_upload_bar.setVisibility(View.VISIBLE);
            tv_upload_num.setVisibility(View.VISIBLE);
        } else if (type == 1) {
            iv_upload_icon.setVisibility(View.VISIBLE);
            iv_upload_icon_mask.setVisibility(View.GONE);
            pb_upload_bar.setVisibility(View.GONE);
            tv_upload_num.setVisibility(View.GONE);
            tv_upload_num.setText("0%");
        } else if (type == 0) {
            iv_upload_icon.setVisibility(View.GONE);
            iv_upload_icon_mask.setVisibility(View.GONE);
            pb_upload_bar.setVisibility(View.GONE);
            tv_upload_num.setVisibility(View.GONE);
            tv_upload_num.setText("0%");
        }
    }


    //=================================上传信息===========================================
    @Override
    public void onSuccessUpload(UploadALiResultBean obj) {
        //更新进度
        if (RefreshUploadHandler != null) {
            Message msg = RefreshUploadHandler.obtainMessage();
            msg.what = 5;
            msg.arg1 = 1;
            RefreshUploadHandler.sendMessage(msg);
        }
        if (uploadType == 1) {
            //上传视频成功
            opusPublishRequestBean.setOpus_file_sign(obj.getmOssTokenResult().getFileInfo().getSign());
            opusPublishRequestBean.setOpus_path(obj.getmOssTokenResult().getFileInfo().getPath());
            //更新进度
            //上传图片
            if (!TextUtils.isEmpty(DyUIAPICallbackImpl.getInstance().getShortVideoFirstClipImgPath())) {
                uploadType = 2;
                uploadPresenter.getOSSTokenAndUploadInfo("opus", "jpg");
                uploadPresenter.setStrUploadPath(DyUIAPICallbackImpl.getInstance().getShortVideoFirstClipImgPath());
                GlideLoader.loadImage(DyUIAPICallbackImpl.getInstance().getShortVideoFirstClipImgPath(), iv_upload_icon);
            } else {
                //上传失败
                refreshUpdateError();
            }

        } else if (uploadType == 2) {
            //上传图片成功
            opusPublishRequestBean.setOpus_cover_sign(obj.getmOssTokenResult().getFileInfo().getSign());
            opusPublishRequestBean.setOpus_cover(obj.getmOssTokenResult().getFileInfo().getPath());
            //上传作品信息到服务器
            uploadType = 4;//业务操作
            uploadPresenter.submintOpusInfo(opusPublishRequestBean);
        } else if (uploadType == 3) {
            //动态图
        } else if (uploadType == 4) {
            //业务操作完成
            if (RefreshUploadHandler != null) {
                Message msg = RefreshUploadHandler.obtainMessage();
                msg.what = 6;
                RefreshUploadHandler.sendMessage(msg);
            }
        }

    }

    @Override
    public void onFailsUpload(UploadALiResultBean obj) {
        if (RefreshUploadHandler != null) {
            Message msg = RefreshUploadHandler.obtainMessage();
            msg.what = 0;
            RefreshUploadHandler.sendMessage(msg);
        }

    }

    @Override
    public void onExceptionUpload(UploadALiResultBean e) {

    }

    @Override
    public void onProgress(OSSRequest request, long currentSize, long totalSize) {
        if (uploadType == 1) {
            //上传视频的进度
        } else if (uploadType == 2) {
            //上传图片
        } else if (uploadType == 3) {
            //上传gift 的进度
        }

    }


    /**
     * tab选中UI 效果
     *
     * @param tab
     * @param isSelected
     */
    public void showTabSelectedUI(TabLayout.Tab tab, boolean isSelected) {
        if (isSelected) {
            homePager.setCurrentItem(tab.getPosition());
            if (tab.getCustomView() instanceof TextView) {
                ((TextView) tab.getCustomView()).setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
                ((TextView) tab.getCustomView()).getPaint().setFakeBoldText(true);
                ((TextView) tab.getCustomView()).setTextColor(getResources().getColor(R.color.bg_white));
            }
        } else {
            if (tab.getCustomView() instanceof TextView) {
                ((TextView) tab.getCustomView()).setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
                ((TextView) tab.getCustomView()).getPaint().setFakeBoldText(false);
                ((TextView) tab.getCustomView()).setTextColor(getResources().getColor(R.color.hh_color_a_five));
            }
        }

    }

    /**
     * 刷新上传作品进度
     */
    private static class RefreshUploadHandler extends Handler {
        WeakReference<MainFragment> weakReference;

        RefreshUploadHandler(MainFragment fragment) {
            weakReference = new WeakReference<>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            MainFragment mainFragment = weakReference.get();
            if (mainFragment != null && msg != null) {
                switch (msg.what) {
                    case 0:
                        //操作错误
                        mainFragment.refreshUpdateError();
                        break;
                    case 1:
                        // 1:开始导出
                        mainFragment.exportVideoStart(msg.getData());
                        break;
                    case 2:
                        //2 ：导出进度
                        mainFragment.refreshExportProgress(msg.arg1);
                        break;
                    case 3:
                        //3：导出成功
                        mainFragment.exportVideoEnd(msg.getData());
                        break;
                    case 4:
                        // 4：上传开始
                        break;
                    case 5:
                        //5：上传进度
                        mainFragment.refreshUploadProgress(msg.arg1);
                        break;
                    case 6:
                        // 6：上传完成
                        mainFragment.refreshUpdateFinish();
                        Message mMsg = this.obtainMessage();
                        mMsg.what = 7;
                        this.sendMessageDelayed(mMsg, 1000);
                        break;
                    case 7:
                        //上传完成后UI
                        mainFragment.refreshUpdateFinishUI();
                        break;
                }

            }
        }
    }

}
